import { useCallback } from 'react';
import { DynamicCrudPage } from '@/components';
import type { TableConfig } from '@/components/DynamicTable/types';
import { getTableConfigByCode } from '@/api/tableConfig';
import { transformTableConfig } from '@/utils/tableConfigTransform';
import { transformEditData, transformSubmitData } from '@/utils/formDataTransform';
import { getDictionaryTypes, createDictionaryType, updateDictionaryType, deleteDictionaryType } from './api';

const DictionaryManagement = () => {
  const fetchConfigApi = useCallback(async (): Promise<TableConfig> => {
    const configRecord = await getTableConfigByCode('dictionaries');
    if (!configRecord) {
      throw new Error('字典表格配置不存在');
    }
    return transformTableConfig(configRecord);
  }, []);

  const wrappedUpdateApi = async (data: any) => {
    const { id, ...updateData } = data;
    return updateDictionaryType(id, updateData);
  };

  const handleTransformFormData = (data: any, mode: 'create' | 'update') => {
    return transformSubmitData(data);
  };

  return (
    <DynamicCrudPage
      fetchConfigApi={fetchConfigApi}
      fetchApi={getDictionaryTypes}
      createApi={createDictionaryType}
      updateApi={wrappedUpdateApi}
      deleteApi={deleteDictionaryType}
      transformEditData={transformEditData}
      transformFormData={handleTransformFormData}
      title="字典管理"
    />
  );
};

export default DictionaryManagement;
